package tech.aistar.controller.client;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import tech.aistar.entity.Picture;
import tech.aistar.entity.User;
import tech.aistar.entity.UserInfo;
import tech.aistar.service.center.IRealNameService;
import tech.aistar.service.center.IUserInfoService;
import tech.aistar.service.client.IUserService;
import tech.aistar.service.demand.IPictureService;
import tech.aistar.util.AliyunSmsUtils;

import javax.servlet.http.HttpSession;



/**
 * @Author: lya
 * @Description: 本类的作用描述:用户登录controller
 * @CreateDate: 2019/10/1
 * @Version: 1.0
 */
@Controller
@RequestMapping("/client")
public class LoginController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private IPictureService pictureService;
    @Autowired
    private IRealNameService iRealNameService;
    /**
     * 用户登录
     */
    @GetMapping("/loginView")
    public String loginView(){
        return "client/login";
    }

    @RequestMapping("/login")
    public ModelAndView login(User u ,String verificationCode, HttpSession session){
        System.out.println("user login start");

        System.out.println("登录session中的用户信息："+ u);
        ModelAndView modelAndView = new ModelAndView();

        User user = userService.findByUsername(u.getUsername());

        UserInfo userInfo = userInfoService.ById(user.getId());

        Picture picture1 = pictureService.findPathById(userInfo.getId());
        session.setAttribute("picture1",picture1);

        System.out.println("这是手机号登录！");
        //取出session的验证码
        String verificationCodeSession = String.valueOf(session.getAttribute("verificationCode"));
        System.out.println("session中的验证码:" +verificationCodeSession);

        //密码解密验证
        if(!verificationCode.equals(verificationCodeSession) && !passwordEncoder.matches(u.getPassword(),user.getPassword())){
            modelAndView.addObject("loginErrorMsg","密码错误");
            modelAndView.addObject("codeError1","验证码错误");
            modelAndView.setViewName("client/login");
        }else{
            session.setAttribute("userId",user.getId());
            session.setAttribute("userinfoId",userInfo.getId());
            session.setAttribute("userInfo",userInfo);
            System.out.println("登录session中的用户信息："+ user);
            System.out.println("登录session中的用户详细信息："+ userInfo);
            modelAndView.setViewName("redirect:/index.jsp");
        }
        return modelAndView;
    }

    /*------------------------------------注册模块----------------------------------------*/
    //用户注册
    /**
     * 用户注册
     */
    @GetMapping("/registerView")
    public String registerView(){
        return "client/register";
    }

    @RequestMapping("/register")
    public ModelAndView register(User u, String verificationCode, HttpSession session){
        System.out.println("验证码：" +verificationCode);

        String password = u.getPassword();
        System.out.println("密码：" +password);

        //取出session的验证码
        String verificationCodeSession = String.valueOf(session.getAttribute("verificationCode"));
        System.out.println("session中的验证码:" +verificationCodeSession);

        //清除session中的验证码和时间
        session.removeAttribute("verificationCode");
        session.removeAttribute("setCodeTime");

        ModelAndView modelAndView = new ModelAndView();
        u.setPassword(password);
        u.setStatus(1);
        u.setPower(1);
        //userService.add(u);
        System.out.println("注册保存的用户:"+u);

        if(verificationCodeSession.equals(verificationCode)){
            System.out.println("输出验证码正确!!!");
            userService.add(u);
            User user1 = userService.findByUsername(u.getUsername());

            UserInfo userInfo = new UserInfo();
            userInfo.setId(user1.getId());
            userInfo.setUserId(user1.getId());
            userInfo.setStatus(0);
            userInfoService.insertUserInfo(userInfo);

            Picture picture = new Picture();
            picture.setId(user1.getId());
            picture.setUserinfoId(user1.getId());
            pictureService.addPathById(picture);

//            RealName realName = new RealName();
//            realName.setId(u.getId());
//            realName.setUserId(u.getId());
//            iRealNameService.save(realName);

            User user= userService.findByUsername(u.getUsername());
            session.setAttribute("user",user);
            modelAndView.setViewName("client/login");
        }else{
            System.out.println("输出验证码错误！");
            //modelAndView.addObject("codeError","验证码错误");
            modelAndView.setViewName("client/register");
        }

        return modelAndView;
    }

    //传送注册验证码
    @RequestMapping("checkVerificationCode")
    public void checkVerificationCode(String registerPhone,HttpSession session){
        System.out.println("接收到的手机号为:" + registerPhone);
        String verificationCode= AliyunSmsUtils.getCode();
        SendSmsResponse response = null;
        try {
            response = AliyunSmsUtils.sendSms(registerPhone,verificationCode);
            System.out.println(verificationCode);
//            System.out.println("短信接口返回的数据----------------");

        } catch (Exception e) {
            e.printStackTrace();

        }
        //将短信验证码绑定在session中
        session.setAttribute("verificationCode",verificationCode);
        Long registerTime=System.currentTimeMillis();
        session.setAttribute("setCodeTime",registerTime);
    }

    //传送登录验证码
    @RequestMapping("checkLoginVerificationCode")
    public void checkLoginVerificationCode(String loginPhone,HttpSession session){
        System.out.println("接收到的手机号为:" + loginPhone);
        String verificationCode= AliyunSmsUtils.getCode();
        SendSmsResponse response = null;
        try {
            response = AliyunSmsUtils.sendSms(loginPhone,verificationCode);
            System.out.println(verificationCode);
//            System.out.println("短信接口返回的数据----------------");

        } catch (Exception e) {
            e.printStackTrace();

        }
        //将短信验证码绑定在session中
        session.setAttribute("verificationCode",verificationCode);
        Long loginTime=System.currentTimeMillis();
        session.setAttribute("setCodeTime",loginTime);
    }


    // 判断手机号是否注册过
    @RequestMapping("isClientRegister")
    @ResponseBody
    public Integer isClientRegister(String registerPhone){
        System.out.println("注册页面收到的手机号：" + registerPhone);
        User user = userService.findByUsername(registerPhone);
        System.out.println("注册时判断的 user:"+user);

        if(user == null){
            return 0;   //用户还未注册
        }else{
            return 1;    //用户已经注册
        }
    }
    //判断手机号在数据库中是否存在
    @RequestMapping("isUserRegister")
    @ResponseBody
    public Integer isUserRegister(String loginPhone){
        System.out.println("登录页面收到的手机号：" + loginPhone);
        User user = userService.findByUsername(loginPhone);
        System.out.println("登录时判断的 user:"+user);

        if(user == null){
            return 0;   //用户不存在
        }else{
            return 1;    //用户已经存在
        }
    }

}
